package com.wangzhen.spring.validation;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
 * spring基于jsr303对Hibernate validtor整合的一个bean检验demo
 */
public class LocalValidatorFactoryBeanDemo {

    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean() {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        return factoryBean;
    }

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor(LocalValidatorFactoryBean localValidatorFactoryBean) {
        MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
        // setValidator 和setValidateFactory 是一样的
        //processor.setValidator(localValidatorFactoryBean.getValidator());
        processor.setValidatorFactory(localValidatorFactoryBean);
        return processor;
    }

    static class User {
        @NotBlank(message = "name not null")
        private String name;
        @NotNull(message = "age not null")
        private Integer age;
    }

    @Validated
    static class UserController {
        public void process(@Valid User user) {
            System.out.println("user=" + user);
        }
    }

    @Bean
    public UserController userController() {
        return new UserController();
    }


    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        context.register(LocalValidatorFactoryBeanDemo.class);

        context.refresh();
        // 打印：第一个是spring内建的Validator对象
        // 打印：第二个是jsr303内建的Validator对象
        // 也就是说这个LocalValidatorFactoryBean实现了这两个接口
        System.out.println(context.getBean(org.springframework.validation.Validator.class));
        System.out.println(context.getBean(javax.validation.Validator.class));
        UserController bean = context.getBean(UserController.class);
        bean.process(new User());


        context.close();
    }
}
